package com.sanq.product.books.interceptors;

import com.sanq.product.books.config.Redis;
import com.sanq.product.books.entity.vo.PermissionVo;
import com.sanq.product.config.utils.string.StringUtil;
import com.sanq.product.config.utils.web.LogUtil;
import com.sanq.product.redis.service.JedisPoolService;
import com.sanq.product.security.interceptors.CheckHasPermissionInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * com.sanq.product.books.interceptors.SecurityInterceptor
 *
 * @author sanq.Yan
 * @date 2019/7/9
 */
public class SecurityInterceptor extends CheckHasPermissionInterceptor {

    @Resource
    private JedisPoolService jedisPoolService;
    private static final int MAX = 60;  //最大限制  1分钟访问60次

    //判断token是否存在
    @Override
    public boolean checkToken(HttpServletRequest request, String token) {
        return jedisPoolService.exists(Redis.ReplaceKey.getSysTokenKey(token));
    }

    //判断是否恶意刷新
    @Override
    public boolean checkIp(HttpServletRequest request, String ip) {
        String ipKey = Redis.ReplaceKey.getCheckIpKey(ip, request.getRequestURI());

        if (jedisPoolService.zrank(Redis.RedisKey.BLOCK_IP_SET, ip)) {
            LogUtil.getInstance(SecurityInterceptor.class).i("ip进入了黑名单");
            return true;
        }


        String ipCountTmp = jedisPoolService.get(ipKey);
        int ipCount = StringUtil.toInteger(ipCountTmp != null ? ipCountTmp : 0);

        if (ipCount > MAX) {
            jedisPoolService.putSet(Redis.RedisKey.BLOCK_IP_SET, 1, ip);
            jedisPoolService.delete(ipKey);
            return true;
        }

        jedisPoolService.incrAtTime(ipKey, MAX);

        return false;
    }

    //判断是否有当前权限
    @Override
    protected boolean checkHasThisUrl(HttpServletRequest httpServletRequest, String uri, String token) {
//        List<PermissionVo> list = JsonUtil.json2ObjList(jedisPoolService.get(Redis.ReplaceKey.getPermissionListKey(token)), PermissionVo.class);

//        return findThisUrl(list, uri);
        return true;
    }

    private boolean findThisUrl(List<PermissionVo> list, String uri) {

        LogUtil.getInstance(getClass()).i(getClass().getSimpleName() + "::" + uri);

        if(list == null || list.isEmpty())
            return false;

        for (int i = 0, size = list.size(); i < size; i++) {
            if (uri.contains(list.get(i).getPermissionUrl())) {
                return true;
            } else
                findThisUrl(list.get(i).getChilds(), uri);
        }

        return false;
    }
}
